package com.gzhryc.socket.message;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.xml.XmlTools;
import com.gzhryc.socket.SocketMessage;
import org.apache.commons.lang3.StringUtils;

public class ByteSocketMessage implements SocketMessage {

    protected byte[] bytes;

    protected Map<String, Object> attributes;

    public ByteSocketMessage() {
    }

    public ByteSocketMessage(byte[] bytes) {
        this.bytes = bytes;
    }

    public ByteSocketMessage(String content) {
        if(StringUtils.isNotBlank(content)) {
            this.bytes = content.getBytes(Charset.forName("UTF-8"));
        }
    }

    @Override
    public byte[] getBytes() {
        return bytes;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }

    @Override
    public String getString() {
        if(this.bytes != null) {
            try {
                return new String(this.bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public String byte2Hex() {
        if (this.bytes == null) {
            return null;
        }
        StringBuilder builder = new StringBuilder("");
        // 遍历byte[]数组，将每个byte数字转换成16进制字符，再拼接起来成字符串
        for (int i = 0; i < this.bytes.length; i++) {
            // 每个byte转换成16进制字符时，bytes[i] & 0xff如果高位是0，输出将会去掉，所以+0x100(在更高位加1)，再截取后两位字符
            builder.append(Integer.toString((this.bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        return builder.toString();
    }

    @Override
    public <T> T fromJSON(Class<T> tClass) {
        String str = getString();
        if(StringUtils.isNotBlank(str)) {
            return JsonTools.fromJson(str, tClass);
        }
        return null;
    }

    @Override
    public <T> T fromXML(Class<T> tClass) {
        String str = getString();
        if(StringUtils.isNotBlank(str)) {
            return XmlTools.changToObject(str, tClass, false);
        }
        return null;
    }

    @Override
    public Object getAttribute(String key) {
        if(attributes != null) {
            return attributes.get(key);
        }
        return null;
    }

    @Override
    public void setAttribute(String key, Object obj) {
        if(attributes == null) {
            attributes = new HashMap<>();
        }
        this.attributes.put(key, obj);

    }
}
